package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.IdCardUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

/**
 * 
 * <pre>
 * 简历
 * </pre>
 * <small> 2020-02-24 21:00:11 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/resumes")
public class ResumesController extends BaseController {
	@Autowired
	private ResumesService resumesService;
	@Autowired
	private UserService userService;
	@Autowired
	private FocusOnResumesService focusOnResumesService;
	@Autowired
	private DictService dictService;
	@Autowired
	private RecruitmentNewsService recruitmentNewsService;
	@Autowired
	private OrganizationNewsService organizationNewsService;
	@Autowired
	private ApplicationRecordService applicationRecordService;
	@GetMapping()
	@RequiresPermissions("jzweb:resumes:resumes")
	String Resumes(){
	    return "jzweb/resumes/resumes";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:resumes:resumes")
	public Result<Page<ResumesDO>> list(ResumesDO resumesDTO){
        Wrapper<ResumesDO> wrapper = new EntityWrapper<ResumesDO>().orderBy("id", false);
		if (org.apache.commons.lang.StringUtils.isNotBlank(resumesDTO.getUserName())){
			Wrapper<UserDO> Wrapper = new EntityWrapper<UserDO>().like("name",resumesDTO.getUserName());
			List<UserDO>  userDOS = userService.selectList(Wrapper);
			String str = "";
			for (UserDO userDO : userDOS){
				str = str + userDO.getId() + ",";
			}
			wrapper.and();
			if(org.apache.commons.lang3.StringUtils.isNotBlank(str)){
				wrapper.in("user_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("user_id",null);
			}
		}
		if (resumesDTO.getDesiredOccupation() != null){
			wrapper.like("desired_occupation",resumesDTO.getDesiredOccupation());
		}

		//查询用户角色
		String roleName = getRoleNames();
		if (!roleName.contains("超级用户角色")) {
			wrapper.eq("state",0);
		}else{
			if (resumesDTO.getState() != null){
				wrapper.eq("state",resumesDTO.getState());
			}
		}

        Page<ResumesDO> page = resumesService.selectPage(getPage(ResumesDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			ResumesDO obj = (ResumesDO) page.getRecords().get(i);
			if (obj.getUserId() != null) {
				UserDO userDO = userService.selectById(obj.getUserId());
				if (userDO != null) {
					if(StringUtils.isNotBlank(userDO.getName())){
						obj.setUserName(userDO.getName());
					}else{
						obj.setUserName(userDO.getUsername());
					}
				}
			}
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:resumes:add")
	String add(){
	    return "jzweb/resumes/add";
	}


	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:resumes:edit")
	String edit(@PathVariable("id") Long id,Model model){
		ResumesDO resumes = resumesService.selectById(id);
		model.addAttribute("resumes", resumes);
	    return "jzweb/resumes/edit";
	}

	@GetMapping("/info/{id}")
	@RequiresPermissions("jzweb:resumes:resumes")
	String info(@PathVariable("id") Long id, Model model) {
		ResumesDO resumes = resumesService.selectById(id);
		if (resumes.getUserId() != null) {
			UserDO userDO = userService.selectById(resumes.getUserId());
			if (userDO != null) {
				resumes.setUserName(userDO.getUsername());
				resumes.setMobile(userDO.getMobile());
				resumes.setSex(userDO.getSex());
				resumes.setHeadPortrait(userDO.getHeadPortrait());
				resumes.setPoliticalAffiliation(userDO.getPoliticalAffiliation());
				resumes.setLiveAddress(userDO.getLiveAddress());
				resumes.setEmail(userDO.getEmail());
				resumes.setDateOfBirth(userDO.getDateOfBirth());
			}
		}
		model.addAttribute("resumes", resumes);
		return "jzweb/resumes/info";
	}
	
	@Log("添加简历")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:resumes:add")
	public Result<String> save( ResumesDO resumes){
		resumesService.insert(resumes);
        return Result.ok();
	}


	@GetMapping("/resumesadd")
	@RequiresPermissions("jzweb:resumes:resumesadd")
	String resumesAdd(Model model,String resuId){
		Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().orderBy("name");
		orWrapper.eq("type",5);
		List<OrganizationNewsDO> list=organizationNewsService.selectList(orWrapper);

		model.addAttribute("resumes", list);
		model.addAttribute("resuId", resuId);
		return "jzweb/resumes/resumesadd";
	}
	/*
	* 新增推荐
	 */
	@Log("选择推荐简历")
	@ResponseBody
	@PostMapping("/resumesSave")
	@RequiresPermissions("jzweb:resumes:resumesadd")
	public ApiResult<?> resumesSave( String id,String resuId){
		//1.根据token获取用户登录数据

		if(StringUtils.isBlank(id)){
			return ApiResult.lack("");//缺少参数
		}
		//查询简历信息
		ResumesDO resumesDO=resumesService.selectById(resuId);

			//查询是否存在这个用户
			UserDO userDO=	userService.selectById(resumesDO.getUserId());
			if(userDO==null){
				return ApiResult.success("该用户不存在！");
			}

			if(resumesDO != null){

				Wrapper<ApplicationRecordDO> orWrapper1 = new EntityWrapper<ApplicationRecordDO>().orderBy("id");
				orWrapper1.eq("user_id",resumesDO.getUserId());
				orWrapper1.eq("rnews_id",id);

				List<ApplicationRecordDO> list=applicationRecordService.selectList(orWrapper1);

				if(list.size()==0){
					ApplicationRecordDO applicationRecordDO1 = new ApplicationRecordDO();
					applicationRecordDO1.setUserId(resumesDO.getUserId());//用户id
					applicationRecordDO1.setOrgId( Long.parseLong(id));//机构id


					Wrapper<RecruitmentNewsDO> orWrapper1s = new EntityWrapper<RecruitmentNewsDO>().orderBy("id");
					orWrapper1s.eq("org_id",id);

					List<RecruitmentNewsDO> listnews=recruitmentNewsService.selectList(orWrapper1s);

					if(listnews.size()==0){
						return ApiResult.success("该企业未发布招聘信息！");
					}
					applicationRecordDO1.setRnewsId(listnews.get(0).getId());//招聘岗位id

					applicationRecordDO1.setAppTime(new Date());//应聘时间
					applicationRecordDO1.setCreaterDate(new Date());//创建时间
					applicationRecordDO1.setState(2);//默认沟通中
					applicationRecordDO1.setType(1);
					boolean b = applicationRecordService.insert(applicationRecordDO1);
					if(b){


						return ApiResult.success("投递成功，请静候佳音！");
					}else{
						return ApiResult.fail("投递失败，请刷新重试！");
					}
				}else{
					return ApiResult.fail("您已投递，请勿重复！");
				}
			}else{
				return ApiResult.fail("信息错误，请刷新重试！");
			}



	}



	@Log("修改简历")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:resumes:edit")
	public Result<String>  update( ResumesDO resumes){
		boolean update = resumesService.updateById(resumes);
		return update ? Result.ok() : Result.fail();
	}

	@Log("关注简历")
	@PostMapping( "/focusRe")
	@ResponseBody
	@RequiresPermissions("jzweb:resumes:add")
	public Result<String>  focusRe( Long id){
		ResumesDO resumesDO = resumesService.selectById(id);
		FocusOnResumesDO focusOnResumesDO = new FocusOnResumesDO();

		focusOnResumesDO.setOrgId(this.getUser().getOrgId());//机构id
		focusOnResumesDO.setUserId(resumesDO.getUserId());//用户id
		focusOnResumesDO.setResumeId(id);//简历id
		focusOnResumesDO.setState(0);//默认正常

		boolean b;
		FocusOnResumesDO focusOnResumesDO1 = focusOnResumesService.selMaxTime(this.getUser().getOrgId());
		if(focusOnResumesDO1 != null){
			if(focusOnResumesDO1.getResidues() <= 0){
				return Result.fail("您关注简历的次数为0,请前往关注简历页面购买后继续！");
			}else{
				focusOnResumesDO.setLookOvers(focusOnResumesDO1.getLookOvers() + 1);//已查看次数
				focusOnResumesDO.setResidues(focusOnResumesDO1.getResidues() - 1);//剩余查看次数
				b = focusOnResumesService.insert(focusOnResumesDO);
			}
		}else{
			Integer focNum = 10;
			Map map = new HashMap();
			map.put("name", "关注简历免费次数");
			map.put("type", "focus_res");
			String focuson = dictService.selDicBy(map);
			if (StringUtils.isNotBlank(focuson)) {
				//判断是否为数字
				if (IdCardUtil.isNumeric(focuson)) {
					focNum = Integer.parseInt(focuson);
				}
			}

			focusOnResumesDO.setLookOvers(1);//已查看次数
			focusOnResumesDO.setResidues(focNum - 1);//剩余查看次数
			b = focusOnResumesService.insert(focusOnResumesDO);
		}

		if(b){
			return Result.ok();
		}else{
			return Result.fail();
		}
	}
	
	@Log("删除简历")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:resumes:remove")
	public Result<String>  remove( Long id){
		resumesService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除简历")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:resumes:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		resumesService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}
	
}
